package com.sfdcj.se.meta.field;

import java.util.HashMap;
import java.util.Hashtable;

import com.sfdcj.se.meta.field.basic.BasicFieldType;
import com.sfdcj.se.meta.field.basic.DateTimeType;
import com.sfdcj.se.meta.field.basic.DateType;
import com.sfdcj.se.meta.field.basic.EmailType;
import com.sfdcj.se.meta.field.basic.PhoneType;
import com.sfdcj.se.meta.field.basic.TextAreaType;
import com.sfdcj.se.meta.field.basic.URLType;

public class FieldTypeBuilder {

	Hashtable<String, FieldType> types = new Hashtable<String, FieldType>();

	public FieldTypeBuilder() {
		init();
	}

	private void init() {
		types.put(AutoNumberType.TYPE, new AutoNumberType());
		types.put(CheckboxType.TYPE, new CheckboxType());
		types.put(CurrencyType.TYPE, new CurrencyType());
		types.put(DateTimeType.TYPE, new DateTimeType());
		types.put(DateType.TYPE, new DateType());
		types.put(EmailType.TYPE, new EmailType());
		types.put(LongTextAreaType.TYPE, new LongTextAreaType());
		types.put(LookupType.TYPE, new LookupType());
		types.put(MasterDetailType.TYPE, new MasterDetailType());
		types.put(MultiPickListType.TYPE, new MultiPickListType());
		types.put(NumberType.TYPE, new NumberType());
		types.put(PercentType.TYPE, new PercentType());
		types.put(PhoneType.TYPE, new PhoneType());
		types.put(PickListType.TYPE, new PickListType());
		types.put(TextAreaType.TYPE, new TextAreaType());
		types.put(TextType.TYPE, new TextType());
		types.put(URLType.TYPE, new URLType());
	}

	public FieldType create(String objfullname, String type, String label,
			String fullname, String attrs) {

		if (type == null || !types.containsKey(type))
			throw new RuntimeException("type:" + type + "is not supported");

		FieldType obj = (FieldType) types.get(type).clone();
		obj.label = label;
		if (!fullname.endsWith("__c"))
			fullname += "__c";
		obj.fullname = fullname;
		obj.objectFullname = objfullname;

		if (obj instanceof BasicFieldType) {
			return obj;
		}

		HashMap<String, String> map = new HashMap<String, String>();
		String[] attrList = attrs.split(";;");
		for (int i = 0; i < attrList.length; i++) {
			String[] attribute = attrList[i].split(":");
			map.put(attribute[0], attribute[1]);
		}
		obj.setAttributes(map);
		return obj;
	}
}
